/*
*	Copyright(c) 2020 lutianming email：641471957@qq.com
*
*	Sheeps may be copied only under the terms of the GNU Affero General Public License v3.0
*/

#include "framework.h"

#ifdef __WINDOWS__
BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
                     )
{
    int i = 0;
    char root_path[MAX_PATH] = { 0x0 };
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
        i = GetModuleFileNameA(NULL, root_path, MAX_PATH);
        while (i > -1)
        {
            if (root_path[i] == '\\' || root_path[i] == '/')
                break;
            else
            {
                root_path[i] = 0x0;
                i--;
            }
        }
        framwork_init(hModule, root_path);
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}
#else
#include "dlfcn.h"
__attribute__((constructor)) void _init(void)  //告诉gcc把这个函数扔到init section  
{
    char root_path[MAX_PATH] = { 0x0 };
    Dl_info dl_info;
    if (dladdr((void*)_init, &dl_info))        //第二个参数就是获取的结果
    {
        snprintf(root_path, MAX_PATH, "%s", dl_info.dli_fname);
        char* p = strrchr(root_path, '/');    //找到绝对路径中最后一个"/"
        *(p + 1) = 0x0;                            //舍弃掉最后“/”之后的文件名，只需要路径
    }
    framwork_init(NULL, root_path);
}

__attribute__((destructor)) void _fini(void)  //告诉gcc把这个函数扔到fini section 
{
}
#endif